#version 440
layout(location = 0) in vec2 qt_TexCoord0;
layout(location = 0) out vec4 fragColor;
layout(binding = 1) uniform sampler2D source;
layout(std140, binding = 0) uniform buf {
    mat4 qt_Matrix;
    float qt_Opacity;
    vec4 color;
	int  mode;
} ubuf;
//PS的颜色叠加算法
void ColorOverlay() {
    vec4 bottomColor = texture(source, qt_TexCoord0);
	vec4 topColor = ubuf.color;
	//如果a为0那么直接返回底层图片颜色,不叠加颜色
	if(topColor.a <= 0) {
		fragColor = bottomColor * ubuf.qt_Opacity;
		return;
	}
	vec3 resColor;
	if(bottomColor.r < 0.5
		&& bottomColor.g < 0.5
		&& bottomColor.b < 0.5) {
		float resRed 	= (bottomColor.r * topColor.r) / 0.5;
		float resGreen  = (bottomColor.g * topColor.g) / 0.5;
		float resBlue   = (bottomColor.b * topColor.b) / 0.5;
		resColor = vec3(resRed, resGreen, resBlue);
	}else {
		float resRed 	= 1 - ((1 - bottomColor.r) * (1 - topColor.r)) / 0.5;
		float resGreen  = 1 - ((1 - bottomColor.g) * (1 - topColor.g)) / 0.5;
		float resBlue   = 1 - ((1 - bottomColor.b) * (1 - topColor.b)) / 0.5;
		resColor = vec3(resRed, resGreen, resBlue);
	}
	
	fragColor = vec4(resColor, bottomColor.a) * ubuf.qt_Opacity;
}
//Qt的颜色叠加算法
void QtColorOverlay() {
	vec4 pixelColor = texture(source, qt_TexCoord0);
	vec3 value1 = mix(pixelColor.xyz/max(pixelColor.w, 0.00390625), ubuf.color.xyz/max(ubuf.color.w, 0.00390625), ubuf.color.w) * pixelColor.w;
	float value2 = pixelColor.w;
	fragColor = vec4(value1,value2) * ubuf.qt_Opacity;
}

void main() {
	if(ubuf.mode == 0) {
		QtColorOverlay();
	}else {
		ColorOverlay();
	}
}
